from functools import cache
from django.core.cache import cache

from rest_framework.views import APIView
from pro import models,serailizer
from rest_framework.response import Response
# Create your views here.
class ProView(APIView):
    def get(self,request):
        key="pro"
        prolist = cache.get(key)
        if prolist:
            return Response({"code":200,"msg":"查询成功","data":prolist})
        prolist = models.Pro.objects.filter(position=0,flag=True).order_by('order')
        ser = serailizer.ProSerializer(prolist,many=True)
        cache.set(key,ser.data,60*60*24)
        return Response({"code":200,"msg":"查询成功","data":ser.data})

class FooterView(APIView):
    def get(self,request):
        fotlist = models.Pro.objects.filter(position=1,flag=True).order_by('order')
        ser = serailizer.ProSerializer(fotlist,many=True)
        return Response({"code":200,"msg":"查询成功","data":ser.data})

class Banner(APIView):
    def get(self,request):
        banlist = models.Pro.objects.filter(flag=True).order_by('order')
        ser = serailizer.ProSerializer(banlist,many=True)
        return Response({"code":200,"msg":"查询成功","data":ser.data})

from rest_framework.generics import ListAPIView
class BannerList(ListAPIView):
    queryset = models.Banner.objects.filter(flag=True).order_by('order')
    serializer_class = serailizer.BannerSerializer


#文件上传的接口
from django.core.files.storage import default_storage
class UploadFile(APIView):
    def post(self,request):
        #获取到上传的文件  参数设置为file
        file=request.data.get("file")
        #如果没有大小和类型的限制就可以直接保存了
        #设置允许的类型
        types=['jpg','png','jpeg']
        if file.name.split(".")[-1] not in types:
            return Response({"code":201,"msg":"上传的文件类型不对"})
        #设置允许的大小 2M  b ->Kb->MB
        if file.size > 2*1024*1024:
            return Response({"code":201,"msg":"上传的文件过大"})
        #default_storage.save(上传后路径以及文件名字，获取的文件对象)
        uploadfile=default_storage.save("banner/"+file.name,file)
        #根据上传后的文件获取到路径
        url=default_storage.url(uploadfile)
        return Response({"url":url})

